package com.custom.base.view

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.custom.base.R
import com.custom.base.util.SDTimerUtil

/**
 * 发送验证码按钮
 */
class SendCodeView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
    private var time:Int //倒计时时间
    private var timeT:Int
    private var defaultStr:String = "Resend Code" //默认显示文本
    private var mTrueBg:Int? = 0
    private var mFalseBg:Int? = 0
    var isSend:Boolean = false
    private val sdTimerUtil: SDTimerUtil =
        SDTimerUtil()
    init {
        val attributes = context.obtainStyledAttributes(attrs, R.styleable.SendCodeView)
        time = attributes.getInteger(R.styleable.SendCodeView_time,60)
        timeT = time
        defaultStr = text.toString()
    }

    private fun update(){
        if(isSend){
            text = "${timeT}s Resend Code"
            isEnabled = false
            mFalseBg?.let { setBackgroundResource(it) }
        }else{
            text = defaultStr
            isEnabled = true
            mTrueBg?.let { setBackgroundResource(it) }
        }
    }

    /**
     * 开始倒计时
     */
    fun startTime(
        trueBg:Int? = null,
        falseBg:Int? = null
    ){
        mTrueBg = trueBg
        mFalseBg = falseBg
        if(!isSend){
            isSend = true
            timeT = time
            sdTimerUtil.startWork(0,1000,object : SDTimerUtil.SDTimerListener{
                override fun onWork() {}
                override fun onWorkMain() {
                    timeT --
                    if(timeT<0){
                        sdTimerUtil.stopWork()
                        isSend = false
                    }
                    update()
                }
            })
        }
    }
}